package com.boxfishedu.foreignkey.service;

import com.boxfishedu.foreignkey.entity.Gender;
import com.boxfishedu.foreignkey.entity.Information;
import com.boxfishedu.foreignkey.entity.Student;
import com.boxfishedu.foreignkey.entity.jpa.StudentJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by lzx on 16/3/9.
 */
@Service
public class StudentService {

    @Autowired
    private StudentJpaRepository studentJpaRepository;

    @Autowired
    InformationService informationService;

    public Student save(Student student) {
        return studentJpaRepository.save(student);
    }

    public Student save(String username, String password, String grade, String gender, String address, int age, String idCard) {
        Student student = new Student();
        student.setUsername(username);
        student.setPassword(password);
        student.setGrade(grade);
        Information information = informationService.findInfo(idCard);
        if (information == null) {
            information = new Information();
            information.setAddress(address);
            information.setAge(age);
            if (gender.equalsIgnoreCase("man")) {
                information.setGender(Gender.MAN);
            } else {
                information.setGender(Gender.WOMAN);
            }
            information.setIdCard(idCard);
        }
        student.setInformation(information);
        return save(student);
    }

    public List<Student> findStudents(String grade) {
        return studentJpaRepository.findByGrade(grade);
    }


    public List<String> nativeFindStudents(String grade) {
        return studentJpaRepository.nativeFindByGrade(grade);
    }

    /**
     * 模糊查询,分页,排序
     *
     * @param username
     * @param page
     * @param size
     * @return
     */
    public List<Student> findStudentsLike(String username, int page, int size) {
        Pageable pageable = new PageRequest(page, size);
        return studentJpaRepository.findByUsernameContains(username, pageable);
    }

    public List<Student> findStudentsContains(String username,String subjectName){
        return studentJpaRepository.findByUsernameAndSubject(username,subjectName);
    }
}
